package com.uidt.project.ptsj.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.uidt.common.constant.Constants;
import com.uidt.common.utils.DateUtils;
import com.uidt.common.utils.SecurityUtils;
import com.uidt.common.utils.StringUtils;
import com.uidt.common.utils.poi.ImportExcelUtilForOneSheet;
import com.uidt.framework.security.LoginUser;
import com.uidt.project.ptsj.domain.PtsjEventLog;
import com.uidt.project.ptsj.mapper.EventInfoMapper;
import com.uidt.project.ptsj.obj.EventForSearch;
import com.uidt.project.system.domain.SysDept;
import com.uidt.project.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.uidt.framework.aspectj.lang.annotation.Log;
import com.uidt.framework.aspectj.lang.enums.BusinessType;
import com.uidt.project.ptsj.domain.EventInfo;
import com.uidt.project.ptsj.service.IEventInfoService;
import com.uidt.framework.web.controller.BaseController;
import com.uidt.framework.web.domain.AjaxResult;
import com.uidt.common.utils.poi.ExcelUtil;
import com.uidt.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 事件信息Controller
 * 
 * @author uidt
 * @date 2024-08-13
 */
@RestController
@RequestMapping("/ptsj/event")
public class EventInfoController extends BaseController
{
    @Autowired
    private IEventInfoService ptsjEventInfoService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private EventInfoMapper ptsjEventInfoMapper;

    private static Map<String,String> map = new HashMap<>();

    static {
        map.put("公安","GA");
        map.put("消防","XF");
        map.put("综合行政","XZ");
        map.put("卫生管理","WS");
        map.put("市场监督","SJ");
    }

    /**
     * 查询事件信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ptsj:event:list')")
    @GetMapping("/list")
    public TableDataInfo list(EventForSearch ptsjEventInfo)
    {
        startPage();
        List<EventInfo> list = ptsjEventInfoService.selectEventInfoList(ptsjEventInfo);
        return getDataTable(list);
    }

    /**
     *app游客查询事件信息列表
     */
    @GetMapping("/appList")
    public TableDataInfo appList(EventInfo ptsjEventInfo)
    {
        startPage();
        List<EventInfo> list = ptsjEventInfoService.selectEventInfoListForApp(ptsjEventInfo);
        return getDataTable(list);
    }
    /**
     * 导出事件信息列表
     */
    @PreAuthorize("@ss.hasPermi('ptsj:event:export')")
    @Log(title = "事件信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EventForSearch ptsjEventInfo)
    {
        List<EventInfo> list = ptsjEventInfoService.selectEventInfoList(ptsjEventInfo);
        ExcelUtil<EventInfo> util = new ExcelUtil<EventInfo>(EventInfo.class);
        util.exportExcel(response, list, "事件信息数据");
    }

    /**
     * 获取事件信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ptsj:event:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(ptsjEventInfoService.selectEventInfoById(id));
    }

    /**
     * 新增事件信息
     */
//    @PreAuthorize("@ss.hasPermi('ptsj:event:add')")
    @Log(title = "事件信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EventInfo ptsjEventInfo)
    {
        return (ptsjEventInfoService.insertEventInfo(ptsjEventInfo));
    }

    /**
     * 用户不登录直接新增事件信息
     */
//    @PreAuthorize("@ss.hasPermi('ptsj:event:add')")
    @Log(title = "用户不登录直接新增事件信息", businessType = BusinessType.INSERT)
    @PostMapping("/noLoginAdd")
    public AjaxResult noLoginAdd(@RequestBody EventInfo ptsjEventInfo)
    {
        return toAjax(ptsjEventInfoService.insertEventInfoNoLogin(ptsjEventInfo));
    }

    /**
     * 修改事件信息
     */
    @PreAuthorize("@ss.hasPermi('ptsj:event:edit')")
    @Log(title = "事件信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EventInfo ptsjEventInfo)
    {
        return toAjax(ptsjEventInfoService.updateEventInfo(ptsjEventInfo));
    }

    /**
     * 删除事件信息
     */
    @PreAuthorize("@ss.hasPermi('ptsj:event:remove')")
    @Log(title = "事件信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ptsjEventInfoService.deleteEventInfoByIds(ids));
    }

    /**
     * 处理事件信息
     */
    @Log(title = "处理事件信息", businessType = BusinessType.UPDATE)
    @PostMapping("/handleEvent")
    public AjaxResult handleEvent(@RequestBody PtsjEventLog eventLog)
    {
        return ptsjEventInfoService.handleEvent(eventLog);
    }






    /**
     * 批量导入事件
     */
    @PostMapping("/batchAddEvent")
    public AjaxResult batchAddEvent(MultipartFile file)
    {
        try{
            // 校验文件类型
            String fileName = file.getOriginalFilename();
            boolean flag = false;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                System.out.println("【"+fileName+"】文件读取中。。。");
                flag = true;
            }else{
                return AjaxResult.error("文件后缀需为.xlsx或.xls");
            }
            String[][] result;
            if (flag) {// 2007Excel
                result = ImportExcelUtilForOneSheet.get2007Data(file.getInputStream(), 1);
            } else {
                // 2003Excel
                result = ImportExcelUtilForOneSheet.get2003Data(file.getInputStream(), 1);
            }

            if(result.length>0){

                LoginUser user = SecurityUtils.getLoginUser();
                List<SysDept> send = sysDeptService.getSnedDeptListByCode(user.getUser().getDept().getDeptcode().split("-")[0]);
                SysDept procDept = null;
                for(int i=0;i<result.length;i++){
                    EventInfo ptsjEventInfo = new EventInfo();

                    String procDeptName = result[i][5];
                    String procSuffix="";
                    for(String key:map.keySet()){
                        if(procDeptName.contains(key)){
                            procSuffix = map.get(key);
                            break;
                        }
                    }

                    if(StringUtils.isEmpty(procSuffix)){
                        continue;
                    }
                    for(SysDept dept:send){
                        if(dept.getDeptcode().endsWith(procSuffix)){
                            procDept = dept;
                            break;
                        }
                    }
//                    String eventId = Constants.EVENT_PREFIX+ DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS);
                    ptsjEventInfo.setEventSource("综治办推送");
                    ptsjEventInfo.setEventId(result[i][0]);
                    ptsjEventInfo.setFeedbackPerson(result[i][2]);
//                    ptsjEventInfo.setFeedbackPhone(result[i][4]);
                    ptsjEventInfo.setEventContent(result[i][3]);
                    ptsjEventInfo.setCreatedTime(DateUtils.parseDate(result[i][6])==null?new Date():DateUtils.parseDate(result[i][6]));
                    ptsjEventInfo.setProcDept(procDept.getDeptName());
                    ptsjEventInfo.setProcDeptCode(procDept.getDeptcode());
                    ptsjEventInfo.setFeedbackUnit(user.getUser().getDept().getDeptName());
                    ptsjEventInfo.setCreatedDeptCode(user.getUser().getDept().getDeptcode());
                    ptsjEventInfo.setCreatedBy(user.getUserId().toString());

                    // 已经回复了的
                    if(StringUtils.isNotEmpty(result[i][8])){
                        ptsjEventInfo.setStatus("0");
                        ptsjEventInfo.setProcOpinions(result[i][8]);
                        ptsjEventInfo.setProcessTime(DateUtils.parseDate(result[i][7])==null?new Date():DateUtils.parseDate(result[i][7]));
                    }else {
                        ptsjEventInfo.setStatus("1");
                    }

                    int count = ptsjEventInfoMapper.insertEventInfo(ptsjEventInfo);
                }
            }

            System.out.println();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println();

        }


        return null;
    }
}
